<?php

namespace Admin\Controller;

use Common\Controller\CommonController;

/**
 * 管理台共通处理
 */
class AdminCommonController extends CommonController
{
    /**
     * 初始化
     */
    function _initialize()
    {
        $flg = $this->isLogin();
        if (!$flg) {
            $this->redirect('/Public/login');
        }

        $this->assign('soft_info' ,$this->soft_info());
    }

    /**
     * 系统配置
     */
    protected function soft_info()
    {
        return array(
            'soft_name'    => C('SYS_SOFT'),
            'comm_name'    => C('SYS_COMM'),
            'homepage'     => C('SYS_HOMEPAGE'),
            'current_year' => C('SYS_CURRENT_YEAR'),
        );
    }

    /**
     * 空跳转
     *
     * @access public
     */
    public function _empty()
    {
        header("HTTP/1.0 404 Not Found");
        $this->display('Public:error-404');
    }

    /**
     * 获取当前Action名称
     * @access protected
     */
    protected function getActionName()
    {
        if (empty($this->name)) {
            // 获取Action名称
            $this->name = substr(get_class($this), 0, -10);

            if (strpos($this->name, '\\')) {
                $nameArr = explode('\\', $this->name);
                $this->name = end($nameArr);
            }
        }
        return $this->name;
    }

    /**
     * 自动登录判断
     */
    protected function isLogin()
    {
        if (isset($_SESSION['adminInfo'])) {
            $account = $_SESSION['adminInfo']['account'];
            $password = $_SESSION['adminInfo']['password'];
        }
        if (isset($_COOKIE['account']) && ($_COOKIE['password'])) {
            $account = $_COOKIE['account'];
            $password = $_COOKIE['password'];
        }
        $input = array (
            'account'  => $account,
            'password' => $password
        );
        $model = M('user');
        $res = $model->field('id')->where($input)->find();
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过session获取用户信息
     *
     * @access public
     */
    protected function getUserInfo()
    {
        $data = session('adminInfo');
        if (isset($data)) {
            return $data;
        } else {
            return false;
        }
    }

    /**
     * 信息详细
     */
    public function detail()
    {
        $id = I('id');
        $model = $this->getActionName();
        if (!(isset($id) && $this->checkInfoAvalible($id, $model))) {
            $this->redirect('Public:error-404');
        }
        $where = array(
            'id' => $id,
        );
        $info = $model->where($where)->find();
        if ($info) {
            $this->assign('info', $info);
        }
        $this->display();
    }

    /**
     * 删除
     */
    public function delData()
    {
        $id = I('id');
        $mode = I('mode', 0, 'int'); // 默认物理删除
        $table =  I('table');
        if (!$id){
            $this->redirect('Public:error-404');
        }
        // 方法验证
        $where = array(
            'id' => $id
        );
        if ($mode === 1) {
            $where['del_flg'] = 1;
        }
//        $model = $this->getActionName();
        $model = M($table);
        $data = $model->field('id')->where($where)->find();
        if(!$data) {
            $this->showMessage(array(), self::ERROR_CODE, '已删除，不能重复操作');
        }
        if ($mode === 1) {
            $res = $model->where($where)->save(array('del_flg' => 1));
        } else {
            $res = $model->where($where)->delete();
        }
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 改变状态
     */
    public function changeStatus()
    {
        $id = I('id');
        $status = I('status');
        $model = I('model');
        if (!$id || !isset($status) || !$model) {
            $code = self::ERROR_CODE;
            $message = self::ERROR_MSG;
            $this->showMessage(array(), $code, $message);
        }
        $data = array(
            'status' => $status,
            'operator_id' => $this->getOperatorId(),
        );
        $res = M($model)->where(array('id' => $id))->save($data);
        if ($res !== false) {
            $code = self::SUCCESS_CODE;
            $message = self::SUCCESS_MSG;
        } else {
            $code = self::ERROR_CODE;
            $message = self::ERROR_MSG;
        }
        $this->showMessage(array(), $code, $message);
    }

    /**
     * 验证id的有效性
     *
     * @param $model
     * @param $id
     * @return bool|mixed
     */
    protected function checkInfoAvalible($id, $model= '')
    {
        if (!$id || !$model) {
            return false;
        }
        $res = M($model)->where(array('id' => $id))->find();
        if (!$res) {
            return false;
        }
        return $res;
    }

    /**
     * 联动: 从数据库获取联动数据(一级)
     *
     * @param $model
     * @return mixed
     */
    protected function getLinkageList($model = 'areas')
    {
        $model = M($model);
        return $model->where(array('level' => 1))->select();
    }

    /**
     * 联动: 联动处理
     *
     * 权限为public, 为了让ajax调用到
     */
    public function linkage()
    {
        $pid    = I('id');
        $level  = I('level');
        $model  = I('model');
        if (!$pid || !$level || !$model) {
            $this->showMessage(array(), self::ERROR_CODE, 'failed');
        }
        $input = array(
            'level' => $level,
            'pid'   => $pid
        );
        // 如果没有2级，返回1级
        $db = M($model);
        $output = $db->where($input)->select();
        if (empty($output)) {
            $output = $db->where(array('id' => I('id')))->select();
        }
        if ($output) {
            $this->showMessage($output);
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 联动: 联动详细
     *
     * @param $id
     * @param $model
     * @param $delimiter
     * @return string
     */
    protected function getLinkageInfoById($id, $model = 'areas', $delimiter = ' ')
    {
        // 数据校验
        if (!$id) {
            return false;
        }
        $m = M($model);
        $data = $m->where(array('id' => $id))->find();
        if (!$data) {
            return false;
        }
        $result = $data['name'];
        // 数据处理
        if ($data['pid'] != 0) { // 不要用严格判断
            // 二级判断
            $data1 = $m->where(array('id' => $data['pid']))->find();
            $result = $data1['name'] . $delimiter . $result;
            // 三级判断
            if ($data1['pid'] != '0') {
                $data2 = $m->where(array('id' => $data1['pid']))->find();
                $result = $data2['name'] .  $delimiter .$result;
            }
        }
        return $result;
    }
}